package com.zego.wawaji.ui.start;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.zego.wawaji.R;
import com.zego.wawaji.base.log.PToast;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.utils.ChineseFilter;
import com.zego.wawaji.http.request.HttpResponse;
import com.zego.wawaji.http.request.RequestComplete;
import com.zego.wawaji.http.request.UrlParam;
import com.zego.wawaji.ui.UIShow;
import com.zego.wawaji.ui.base.BaseAppCompatActivity;
import com.zego.wawaji.ui.bean.LoginResult;
import com.zego.wawaji.ui.dialog.LoadingDialog;
import com.zego.wawaji.wawaji_client.App;
import com.zego.wawaji.wawaji_client.util.NoDoubleClickListener;
import com.zego.wawaji.wawaji_client.util.OnSoundClickListener;

import java.lang.ref.WeakReference;

/**
 * 手机号登陆
 */
public class RegMobileAct extends BaseAppCompatActivity implements RequestComplete {
    private EditText edtPhone, edtCode;
    private TextView getCode;
    private String phone, code;

    private final TimeHandler handler = new TimeHandler(this);
    private SendEnableThread sendthread = null;

    private boolean isLogin = false;  // 是否可进行验证码校验操作

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reg_mobile_act);
        initView();
    }

    private void initView() {
        edtPhone = (EditText) findViewById(R.id.login_mobile);
        edtCode = (EditText) findViewById(R.id.login_code);
        getCode = (TextView) findViewById(R.id.login_get_code);
        getCode.setOnClickListener(clickListener);
        findViewById(R.id.login_btn).setOnClickListener(soundListener);
    }

    private NoDoubleClickListener clickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.login_get_code: // 获取验证码
                    if (validPhone()) {
                        ModuleMgr.getLoginMgr().reqSendCode(phone, RegMobileAct.this);
                    }
                    break;
            }
        }
    };

    private OnSoundClickListener soundListener = new OnSoundClickListener() {
        @Override
        public void onSoundClick(View v) {
            switch (v.getId()) {
                case R.id.login_btn:    // 手机号验证码登陆
                    sendCode();
                    break;
                default:
                    break;
            }
        }
    };

    private void sendCode() {
        code = edtCode.getText().toString();
        if (isLogin && !TextUtils.isEmpty(code)) {
            LoadingDialog.show(this, "登录中...");
            ModuleMgr.getLoginMgr().reqVerifyCode(phone, code, RegMobileAct.this);
            return;
        }
        PToast.showShort("验证码错误");
    }

    private boolean validPhone() {
        phone = edtPhone.getText().toString();
        if ("".equals(phone)) {
            PToast.showShort("手机号码不能为空");
            return false;
        }
        if (!ChineseFilter.isPhoneNumber(phone)) {
            PToast.showShort("手机号格式不正确");
            return false;
        }
        return true;
    }

    @Override
    protected boolean isImmersionBar() {
        return false;
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        PToast.showShort(response.getMsg());

        // 发送验证码
        if (response.getUrlParam() == UrlParam.reqSendCode) {
            isLogin = response.isOk();
            if (response.isOk()) {
                LoginResult data = (LoginResult) response.getBaseData();
                App.isNewUser = data.isNew();

                if (sendthread == null || sendthread.getState() == Thread.State.TERMINATED) {
                    sendthread = new SendEnableThread();
                    getCode.setClickable(false);
                    sendthread.start();
                }
            }
            return;
        }

        // 手机验证码验证
        if (response.getUrlParam() == UrlParam.reqVerifyCode) {
            LoadingDialog.closeLoadingDialog(500);
            if (!response.isOk()) return;

            LoginResult data = (LoginResult) response.getBaseData();
            ModuleMgr.getLoginMgr().setCookie(data.getAuth());
            ModuleMgr.getLoginMgr().putAllLoginInfo(data.getUid(), true);
            UIShow.showMainClearTask(RegMobileAct.this);
        }
    }

    private static class TimeHandler extends Handler {
        private final WeakReference<RegMobileAct> mActivity;

        TimeHandler(RegMobileAct act) {
            this.mActivity = new WeakReference<>(act);
        }

        @Override
        public void handleMessage(Message msg) {
            RegMobileAct act = mActivity.get();
            if (act != null) {
                if (msg.what > 0) {
                    act.getCode.setTextColor(act.getResources().getColor(R.color.text_red));
                    act.getCode.setText(String.format("%1$dS", msg.what));
                } else {
                    act.getCode.setTextColor(act.getResources().getColor(R.color.text_gray));
                    act.getCode.setText("重新获取");
                    act.getCode.setClickable(true);
                }
            }
        }
    }

    private class SendEnableThread extends Thread {
        public void run() {
            int count = 60;
            while (count >= 0) {
                try {
                    Thread.sleep(1000);
                    handler.sendEmptyMessage(count);
                } catch (Exception e) {
                    break;
                }
                count--;
            }
        }
    }
}
